﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using DAL;

namespace WebAPI.Controllers
{
    public class DroitController : ApiController
    {
        private MyTeamEntities db = new MyTeamEntities();

        // GET api/Droit
        public IQueryable<Droit> GetDroits()
        {
            return db.Droits;
        }

        // GET api/Droit/5
        [ResponseType(typeof(Droit))]
        public IHttpActionResult GetDroit(int id)
        {
            Droit droit = db.Droits.Find(id);
            if (droit == null)
            {
                return NotFound();
            }

            return Ok(droit);
        }

        // PUT api/Droit/5
        public IHttpActionResult PutDroit(int id, Droit droit)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != droit.Dro_Id)
            {
                return BadRequest();
            }

            db.Entry(droit).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!DroitExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return StatusCode(HttpStatusCode.NoContent);
        }

        // POST api/Droit
        [ResponseType(typeof(Droit))]
        public IHttpActionResult PostDroit(Droit droit)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.Droits.Add(droit);
            db.SaveChanges();

            return CreatedAtRoute("DefaultApi", new { id = droit.Dro_Id }, droit);
        }

        // DELETE api/Droit/5
        [ResponseType(typeof(Droit))]
        public IHttpActionResult DeleteDroit(int id)
        {
            Droit droit = db.Droits.Find(id);
            if (droit == null)
            {
                return NotFound();
            }

            db.Droits.Remove(droit);
            db.SaveChanges();

            return Ok(droit);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }

        private bool DroitExists(int id)
        {
            return db.Droits.Count(e => e.Dro_Id == id) > 0;
        }
    }
}